package com.xz.simplerpc.rpc;

import com.xz.simplerpc.constants.Constants;
import com.xz.simplerpc.extension.ExtensionLoader;
import com.xz.simplerpc.extension.URL;
import com.xz.simplerpc.rpc.api.Invoker;
import com.xz.simplerpc.rpc.api.Protocol;
import com.xz.simplerpc.rpc.proxy.JdkProxyFactory;

/**
 * Created by fingal on 2018/1/7.
 */
public class ReferenceConfig<T> {
    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

    private JdkProxyFactory jdkProxyFactory = new JdkProxyFactory();

    private RegistryConfig registryConfig;

    private Class<T> interfaceClass;

    public void setInterfaceClass(Class<T> interfaceClass) {
        this.interfaceClass = interfaceClass;
    }

    public void setRegistryConfig(RegistryConfig registryConfig) {
        this.registryConfig = registryConfig;
    }

    public T get() {
        URL registryUrl = URL.valueOf(registryConfig.getAddress())
                            .setServiceInterface(interfaceClass.getName())
                            .addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE);
        Invoker<T> invoker = protocol.refer(interfaceClass, registryUrl);
        return (T) jdkProxyFactory.getProxy(invoker, new Class<?>[]{interfaceClass});
    }
}
